const mongo = require('../db/mongo')
const { ObjectID } = require('mongodb')
const COLLECTION = 'items'

/**
 * 获取项目列表
 * @param {string} author 
 */
const getList = async (author) => {
  author ? author = { author } : author = {}
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).find(author).toArray()
}

/**
 * 获取项目详情
 * @param {object} query 
 */

const getDetail = async (query) => {
  if (query._id) query._id = ObjectID(query._id)
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).find(query).toArray()
}
/**
 * 发布项目
 * @param {object} article 
 * @param {string} author 
 */

const publish = async (article, author) => {
  Object.assign(article, { author })
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).insertOne(article)
}

/**
 * 更新项目
 * @param {object} query 
 * @param {string} author 
 */
const update = async (query, author) => {
  if (query._id) query._id = ObjectID(query._id)
  Object.assign(query, { author })
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).updateOne({_id: query._id}, {
    $set: query
  })
}

/**
 * 删除项目
 * @param {object} query 
 */
const del = async (query) => {
  if (query._id) query._id = ObjectID(query._id)
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).deleteOne(query)
}

module.exports = {
  getList,
  getDetail,
  publish,
  update,
  del
}
